import React, { useEffect } from 'react';
import {
  Select,
  Pagination,
  DatePicker,
  Button,
  Form,
  message,
  Drawer,
  ConfigProvider,
} from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import { useDebounceFn } from 'ahooks';
import moment from 'moment';
import _ from 'lodash';

import { HttpCode } from '#/utils/contacts.js';
import { PageLoading, TRDefault } from '@/components/index.js';
// import { TjStation } from '@/pages/ETrade/components/index.js';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';

import { tableHead, tabOption, tabOption_1, imgString_2 } from '../../helper.js';
import {
  powerGenerationPlanList,
  publishPowerGenerationPlan,
  delPowerGenerationPlan,
  useNewServers,
} from '../../services.js';
import { BordTable } from '../BaseTable';
import GenerationPlan from '../GenerationPlan';
import styles from './index.less';

const PowerGenerationPlanSurvey = (props: any) => {
  const {
    options = [] as any,
    treeData = [],
    optionAll = [],
    status = 'null',
    reSize,
    year,
    formDataValues,
    defaultItem = {} as any,
    treeHljData = [],
    province = [],
    searchMarketId = '',
  } = props;

  const [currentActive, setCurrentActive] = React.useState(status),
    [tableData, setTableData] = React.useState<any>([]),
    [isLoding, setIsLoding] = React.useState(true),
    [pageSize, setPageSize] = React.useState(50),
    [currentPage, setCurrentPage] = React.useState(1),
    [total, setTotal] = React.useState(0),
    [visible, setVisible] = React.useState(false),
    [selectData, setSelectData] = React.useState(),
    [editable, setEditable] = React.useState(true),
    [filterParams, setFilterParams] = React.useState<any>(), // 保存筛选条件
    [formData, setFormData] = React.useState<any>({}),
    [tradingUnitList, setTradingUnitList] = React.useState<any>([...formDataValues.stationIdList]),
    [form] = Form.useForm();

  const [currentProvinceInfo, setCurrentProvinceInfo] = React.useState<any>();
  const [curMarketId, setCurMarketId] = React.useState(''); //缓存当前选中的marketId

  useEffect(() => {
    // province 是父组件传的交易中心下拉选项
    if (province.length > 0) {
      if (searchMarketId) {
        // 选第一个交易中心作为默认
        changeMarketId(searchMarketId);
        //父组件检索的marketId——>value
        setCurMarketId(searchMarketId);
      } else {
        // 选第一个交易中心作为默认
        changeMarketId(province[0]?.value);
        setCurMarketId(province[0]?.value);
      }
    }
  }, [province]);

  const _look = (record: any) => {
    if (
      record.planStatus !== '已完成' &&
      record.planStatus !== '待发布' &&
      record.planStatus !== '修改待发布'
    )
      return;
    setSelectData(record);
    setEditable(false);
    setVisible(true);
  };

  //通过stationId去查找marketId
  const getMarketId = (unit: string) => {
    const result = options.find((item: any) => item.stationId === unit);
    let _marketId = '';
    if (result) {
      _marketId = result.marketId;
    }
    return _marketId;
  };

  const _delete = async (record: any) => {
    if (record.planStatus !== '修改待发布') return;
    const marketId = getMarketId(record.unitId);

    let data: any = {
      planId: record.planId,
    };

    if (useNewServers.includes(marketId)) {
      data = {
        ...data,
        marketId,
      };
    }
    // const res = await delPowerGenerationPlan({ planId: record.planId }, marketId).catch();
    const res = await delPowerGenerationPlan(data, marketId).catch();
    if (res?.statusCode === HttpCode.SUCCESS) {
      message.success('删除成功');
      form.submit();
    } else {
      message.error('删除失败');
    }
  };

  const _editor = async (record: any) => {
    setSelectData(record);
    setEditable(true);
    setVisible(true);
  };

  const _public = async (record: any) => {
    if (record.planStatus !== '待发布' && record.planStatus !== '修改待发布') return;
    const marketId = getMarketId(record.unitId);

    let data: any = {
      stationId: record.unitId,
      year: moment(record.planDateTime).format('YYYY'),
      planId: record.planId,
    };

    if (useNewServers.includes(marketId)) {
      data = {
        ...data,
        marketId,
      };
    }

    const res = await publishPowerGenerationPlan(
      // {
      //   stationId: record.unitId,
      //   year: moment(record.planDateTime).format('YYYY'),
      //   planId: record.planId,
      // },
      data,
      marketId,
    ).catch();
    if (res?.statusCode === HttpCode.SUCCESS) {
      message.success('发布成功');
      form.submit();
    } else {
      message.error('发布失败');
    }
  };

  //交易中心改变事件
  const changeMarketId = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      setCurrentProvinceInfo(item);
      setCurMarketId(item.value);
      form.setFieldsValue({
        stationIdList: item.stations.map((v: StationType) => {
          return v.stationId;
        }),
      });
    }
  };

  const getNewTableData = (data: any) => {
    return (data || []).map((t: any) => {
      return {
        unit: t.stationName,
        planStatus: tabOption_1.find((_t: any) => t.status === _t.value)?.label,
        status: t.status,
        yearPlanTotal: t.yearEle,
        publicPlan: t.planDateTime,
        opUserName: t.opUserName,
        planId: t.planId,
        unitId: t.stationId,
      };
    });
  };
  const searchData = async (param: any) => {
    const res = await powerGenerationPlanList(param, curMarketId).catch();
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (!res.data) return;
      const data = res.data;
      const _temp = getNewTableData(data.records);
      _temp.map((t: any) => {
        t.operation = () => (
          <span>
            <span
              className={styles.custorm}
              onClick={() => {
                _editor(t);
              }}
            >
              编辑
            </span>
            <span style={{ margin: '0 8px', color: 'var(--bd-a50)' }}>|</span>
            <span
              className={`${
                t.planStatus === '已完成' ||
                t.planStatus === '待发布' ||
                t.planStatus === '修改待发布'
                  ? styles.custorm
                  : styles.disable
              }`}
              onClick={() => {
                _look(t);
              }}
            >
              查看
            </span>
            <span style={{ margin: '0 8px', color: 'var(--bd-a50)' }}>|</span>
            <span
              className={`${
                t.planStatus === '待发布' || t.planStatus === '修改待发布'
                  ? styles.custorm
                  : styles.disable
              }`}
              onClick={() => {
                _public(t);
              }}
            >
              发布
            </span>
            <span style={{ margin: '0 8px', color: 'var(--bd-a50)' }}>|</span>
            <span
              className={`${t.planStatus === '修改待发布' ? styles.custorm : styles.disable}`}
              onClick={() => {
                _delete(t);
              }}
            >
              删除
            </span>
          </span>
        );
        return t;
      });
      setTotal(res.data.total);
      setTableData(_temp);
    }
  };
  const _tabChange = (activeKey: any) => {
    setCurrentActive(activeKey);
  };
  const _changeSize = (page: any, Size: any) => {
    setPageSize(Size);
    setCurrentPage(page);
  };

  React.useEffect(() => {
    form.submit();
  }, [pageSize, currentPage]);

  const _onFinish = useDebounceFn(
    async (values: any) => {
      setIsLoding(false);
      setTableData([]);
      setFormData(values);
      const isDate = filterParams?.date !== values.date,
        isTab = filterParams?.tab !== values.tab,
        // isUnit = filterParams?.unit !== values.unit;
        isUnit = filterParams?.stationIdList !== values.stationIdList;
      let _currentPage = currentPage;
      //筛选条件改变 切换页码为第一页
      if (isDate || isTab || isUnit) {
        //保存改变后的参数
        setFilterParams({
          date: values.date,
          tab: values.tab,
          stationIdList: values.stationIdList,
        });
        setCurrentPage(1);
        _currentPage = 1;
      }

      const param: any = {
        current: _currentPage,
        size: pageSize,
        status: values.tab === 'null' ? null : values.tab,
        stationIdList: tradingUnitList,
        stationNameList: tradingUnitList.map(
          (t: any) => options.find((_t: any) => t === _t.value)?.label,
        ),
        // stationIdList: values.stationIdList,
        // stationNameList: values.stationIdList.map(
        //   (t: any) => options.find((_t: any) => t === _t.value)?.label,
        // ),
        year: moment(values.date).format('YYYY'),
      };
      if (useNewServers.includes(curMarketId)) {
        param.marketId = curMarketId;
      }
      await searchData(param);
      setIsLoding(true);
    },
    { wait: 500 },
  );

  const onSave = () => {
    setVisible(false);
    form.submit();
  };

  const _renderContent = () => {
    if (!isLoding) return <PageLoading />;
    if (!tableData.length) return <TRDefault type="emptysm" />;
    return (
      <>
        <BordTable tableData={tableData} tableHeader={tableHead} />
        <div className={styles.flex}>
          <Pagination
            current={currentPage}
            total={total}
            size="small"
            showSizeChanger
            showQuickJumper
            pageSize={pageSize}
            onChange={_changeSize}
          />
          <Drawer
            className={styles._drawer}
            title={
              <div className={styles.title}>
                <img src={imgString_2} />
                <div className={styles.iconText}>发电计划</div>
              </div>
            }
            width={1400}
            onClose={() => {
              setVisible(false);
            }}
            visible={visible}
          >
            {visible ? (
              <GenerationPlan
                stations={options}
                reSize={reSize}
                selectData={selectData}
                save={onSave}
                year={formData.date}
                editable={editable}
                {...props}
              />
            ) : (
              ''
            )}
          </Drawer>
        </div>
      </>
    );
  };
  const initMarketId = () => {
    if (searchMarketId) {
      return searchMarketId;
    }
    if (province.length > 0) {
      return province[0].value;
    }
    return '';
  };
  const initialValues = () => {
    // if (!optionAll.length) return;
    if (!treeHljData.length) return;
    return {
      date: moment(year),
      tab: currentActive,
      unit: optionAll,
      // marketId: province.length > 0 ? province[0].value : '',
      marketId: initMarketId(),
    };
  };
  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.header}>
        <Form
          form={form}
          initialValues={initialValues()}
          className={styles.formStyles}
          onFinish={_onFinish.run}
        >
          <Form.Item name="date" className={styles.cell_item}>
            <DatePicker className={styles.select_date} picker="year" />
          </Form.Item>
          <Form.Item name="tab" className={styles.cell_item}>
            <Select
              className={styles.filter_tab}
              showSearch
              placeholder="全部计划状态"
              onChange={_tabChange}
              options={tabOption}
              filterOption={(input, option) => {
                return (option?.label as unknown as string)
                  .toLowerCase()
                  .includes(input.toLowerCase());
              }}
            />
          </Form.Item>
          {/* <Form.Item name="unit" className={styles.cell_item}>
            <TjStation width={140} options={treeData} />
          </Form.Item> */}

          <Form.Item name="marketId" className={styles.marketId_item}>
            <Select
              options={province}
              style={{ width: 180 }}
              placeholder="请选择交易中心"
              onChange={changeMarketId}
            />
          </Form.Item>

          <Form.Item name="stationIdList" className={styles.marketId_item}>
            <TjMarketingUnit
              treeData={treeHljData}
              marketId={currentProvinceInfo?.value}
              setTradingUnitList={setTradingUnitList}
              tradingUnitList={tradingUnitList}
            />
          </Form.Item>

          <Button className={styles.submit} type="primary" htmlType="submit">
            查询
          </Button>
        </Form>
        {_renderContent()}
      </div>
    </ConfigProvider>
  );
};

export default PowerGenerationPlanSurvey;
